#include "widget.h"
#include "ui_widget.h"
#include <QDebug>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    // 设置根节点的内容
    ui->treeWidget->setHeaderLabel("动物");

    // 给顶层节点添加子节点
    QTreeWidgetItem* item1 = new QTreeWidgetItem();
    item1->setText(0, "猫");
    ui->treeWidget->addTopLevelItem(item1);

    QTreeWidgetItem* item2 = new QTreeWidgetItem();
    item2->setText(0, "狗");
    ui->treeWidget->addTopLevelItem(item2);

    QTreeWidgetItem* item3 = new QTreeWidgetItem();
    item3->setText(0, "猪");
    ui->treeWidget->addTopLevelItem(item3);

    // 给顶层节点添加子节点
    QTreeWidgetItem* item1_child1 =  new QTreeWidgetItem();
    item1_child1->setText(0, "好猫");
    QTreeWidgetItem* item1_child2 =  new QTreeWidgetItem();
    item1_child2->setText(0, "中猫");
    QTreeWidgetItem* item1_child3 =  new QTreeWidgetItem();
    item1_child3->setText(0, "坏猫");

    item1->addChild(item1_child1);
    item1->addChild(item1_child2);
    item1->addChild(item1_child3);

}

Widget::~Widget()
{
    delete ui;
}


void Widget::on_pushButton_clicked()
{
    const QString& content = ui->lineEdit->text();
    if(content.isEmpty())
        return;

    QTreeWidgetItem* item = new QTreeWidgetItem();
    item->setText(0, content);
    ui->treeWidget->addTopLevelItem(item);
}

void Widget::on_pushButton_2_clicked()
{
    QTreeWidgetItem* selected =  ui->treeWidget->currentItem();
    if(selected == nullptr)
        return;

    const QString& content = ui->lineEdit->text();
    if(content.isEmpty())
        return;

    QTreeWidgetItem* item = new QTreeWidgetItem();
    item->setText(0, content);
    selected->addChild(item);
}

void Widget::on_pushButton_3_clicked()
{
    QTreeWidgetItem* selected =  ui->treeWidget->currentItem();
    if(selected == nullptr)
    {
        qDebug() << "没有选中节点，或者选中的节点不是顶层节点";
        return;
    }

    QTreeWidgetItem* parent = selected->parent();
    if(parent == nullptr)
    {
        // 说明是顶层元素
        int index = ui->treeWidget->indexOfTopLevelItem(selected);
        if(index < 0)
            return;

        ui->treeWidget->takeTopLevelItem(index);
    }
    else
    {
        // 说明是子节点
        parent->removeChild(selected);
    }
}
